//
//  VisitingViewController.m
//  移动营销
//
//  Created by Hanen 3G 01 on 16/2/23.
//  Copyright © 2016年 Hanen 3G 01. All rights reserved.
//

#import "VisitingViewController.h"
#import "CKCalendarView.h"
#import "CRM_PrefixHeader.pch"
#import "VisitTableViewCell.h"
#import "MyClientView.h"
#import "Toast+UIView.h"
#import "SelectViewController.h"
#import "SelectStaffView.h"
#import "MyTabBarController.h"
#import "NewVisitViewController.h"

@interface VisitingViewController ()<MyClientViewDelegate>

@property(nonatomic) BOOL isManager;
@property(nonatomic) BOOL isMyVisit;
@property(nonatomic, strong) MyClientView *topBtnView;
@property (strong, nonatomic) UITableView *visitTableView;
@property (strong, nonatomic) CKCalendarView *calendar;
@property (strong, nonatomic) UIView *backView;
@property (strong, nonatomic) SelectStaffView *selectStaffView;

/**
 *  我的拜访
 */
@property(nonatomic,strong)UITableView     *myVisitTableView;
@property(nonatomic,strong)UIView          *myVisitView;

/**
 *  下属拜访
 */
@property(nonatomic,strong)UITableView     *otherVisitTableView;
@property(nonatomic,strong)UIView          *otherVisitView;

@end

@implementation VisitingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.hidesBackButton =YES;
    CGFloat statusBarHeight = 0;
    if ([[UIDevice currentDevice].systemVersion floatValue] <= 7.0)
    {
        statusBarHeight = 20;
    }

    self.navigationItem.rightBarButtonItem = [ViewTool getBarButtonItemWithTarget:self WithString:@"新建" WithAction:@selector(clickToNewVisit)];
    NSString *type = [[[NSUserDefaults standardUserDefaults] objectForKey:@"type"] stringValue];

    if ([type isEqualToString:@"2"]) {
        _isManager = YES;
        self.navigationItem.title = @"";
        
        _topBtnView = [[MyClientView alloc] initWithFrame:CGRectMake(0, 0, [UIView getWidth:200], 44) withLeftTitle:@"下属拜访" andRightTitle:@"我的拜访"];
        _topBtnView.delegate = self;
        self.navigationItem.titleView = _topBtnView;
        
        UILabel *lineLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 43, KSCreenW, 0.5)];
        lineLabel.backgroundColor = grayLineColor;
        [_topBtnView addSubview:lineLabel];
        
    }else{
        _isManager = NO;
        self.navigationItem.title = @"我的拜访";
    }
    
    _visitTableView.delegate=self;
    _visitTableView.dataSource=self;
    
//    _calendar = [[CKCalendarView alloc] initWithStartDay:startSunday];//开始日期
//    _calendar.frame = CGRectMake(0, statusBarHeight+44, KSCreenW, 200);

    self.view.userInteractionEnabled = YES;
    _calendar = [[CKCalendarView alloc] initWithStartDay:startSunday frame:CGRectMake(0, 20+44, KSCreenW, 100)];//开始日期
    _calendar.userInteractionEnabled = YES;
    UISwipeGestureRecognizer* recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)];
    // handleSwipeFrom 是偵測到手势，所要呼叫的方法
//    recognizer.direction = UISwipeGestureRecognizerDirectionDown;
    NSLog(@"%lu-------",(unsigned long)recognizer.direction);
    // 不同的 Recognizer 有不同的实体变数
    // 例如 SwipeGesture 可以指定方向
    // 而 TapGesture 則可以指定次數
    //    recognizer.direction = UISwipeGestureRecognizerDirectionUp
    [_calendar addGestureRecognizer:recognizer];
    NSLog(@"%f",_calendar.height);
    
    [self.view addSubview:_calendar];
        NSLog(@"%f!!!",_calendar.height);
//    //    __unsafe_unretained __typeof(self) weakSelf = self;
//    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
//    _visitTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        //        [weakSelf loadNewData];
//        [self loadNewData];
//    }];
//    
//    // 马上进入刷新状态
//    [_visitTableView.mj_header beginRefreshing];
//    
//    
//    _visitTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
//        //        [weakSelf loadMoreData];
//        [self loadMoreData];
//    }];
    UILabel *planbLab = [[UILabel alloc] initWithFrame:CGRectMake1(20,statusBarHeight+44+310, 100, 20)];
    planbLab.text = @"今日计划:6";
    planbLab.textColor = grayFontColor;
    planbLab.font = [UIFont systemFontOfSize:16];
    [self.view addSubview:planbLab];
    UILabel *completedLab = [[UILabel alloc] initWithFrame:CGRectMake1(130,statusBarHeight+44+310, 90, 20)];
    completedLab.text = @"已完成:1";
    completedLab.textColor = grayFontColor;
    completedLab.font = [UIFont systemFontOfSize:16];
    [self.view addSubview:completedLab];
    UILabel *notCompletedLab = [[UILabel alloc] initWithFrame:CGRectMake1(230,statusBarHeight+44+310, 90, 20)];
    notCompletedLab.text = @"未完成:5";
    notCompletedLab.textColor = darkOrangeColor;
    notCompletedLab.font = [UIFont systemFontOfSize:16];
    [self.view addSubview:notCompletedLab];
    
    UILabel *lineLab = [[UILabel alloc] initWithFrame:CGRectMake3(20, statusBarHeight+44+310+29, KSCreenW-40, 1)];
    lineLab.layer.borderWidth = 10;
    lineLab.layer.borderColor = [grayLineColor CGColor];
    [self.view addSubview:lineLab];
    
    
    _visitTableView=[[UITableView alloc]initWithFrame:CGRectMake3(0, statusBarHeight+44+340, KSCreenW, KSCreenH-statusBarHeight-44-340-TabbarH) style:UITableViewStylePlain];
    _visitTableView.delegate=self;
    _visitTableView.dataSource=self;
    _visitTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_visitTableView];
    
    [self reloadData];
    NSLog(@"%f",self.navigationItem.titleView.height);
    
    CGRect rectStaus = [[UIApplication sharedApplication] statusBarFrame];
    NSLog(@"staus width:%f",rectStaus.size.width);
        NSLog(@"staus height:%f",rectStaus.size.height);
    
    CGRect rectNav = self.navigationController.navigationBar.frame;
    NSLog(@"nav width:%f",rectNav.size.width);
    NSLog(@"nav height:%f",rectNav.size.height);
//    NSLog(@"%f",self.navigationController.);
    
}

- (void)reloadData{
    
    if (_isManager) {
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        NSString *uid = [[userDefaults objectForKey:@"uid"] stringValue];
        NSString *token = [userDefaults objectForKey:@"token"];
        
//        NSDate *now = [NSDate date];
//        NSCalendar *calendar = [NSCalendar currentCalendar];
//        NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
//        NSDateComponents *dateComponent = [[NSDateComponents alloc] init];
//        dateComponent = [calendar components:unitFlags fromDate:now];
//        NSInteger year = [dateComponent year];
//        NSInteger month = [dateComponent month];
//        NSInteger day = [dateComponent day];
        
//        NSCalendar *greCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
//        //  通过已定义的日历对象，获取某个时间点的NSDateComponents表示，并设置需要表示哪些信息（NSYearCalendarUnit, NSMonthCalendarUnit, NSDayCalendarUnit等）
//        NSDateComponents *dateComponents = [greCalendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:[NSDate date]];

//        NSInteger year = [dateComponents year];
//        NSInteger month = [dateComponents month];
//        NSInteger day = [dateComponents day];
        
        NSDictionary * params1 = [NSDictionary dictionaryWithObjectsAndKeys:uid, @"uid", token, @"token",nil, @"year", nil, @"month", nil];
        AFHTTPRequestOperationManager * manager1 = [AFHTTPRequestOperationManager manager];
        manager1.requestSerializer.timeoutInterval = 20;
        [manager1 POST:GET_MONTH_VISIT_URL parameters:params1 success:^(AFHTTPRequestOperation *operation, id responseObject) {
            [self.view hideToastActivity];
            NSLog(@"%@",responseObject);
            int code = [[(NSDictionary *)responseObject objectForKey:@"code"] intValue];
            if(code != 100)
            {
                NSString * message = [(NSDictionary *)responseObject objectForKey:@"message"];
                [self.view makeToast:message];
                NSLog(@"%@",message);
                
            }else{
                
            }
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"%@",error);
            [self.view hideToastActivity];
            [self.view makeToast:@"登录失败"];
        }];

        
        NSDictionary * params = [NSDictionary dictionaryWithObjectsAndKeys:uid, @"uid", token, @"token",nil, @"year", nil, @"month",nil, @"day", nil];
        AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
        manager.requestSerializer.timeoutInterval = 20;
        [manager POST:GET_VISIT_URL parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
            [self.view hideToastActivity];
            NSLog(@"%@",responseObject);
            int code = [[(NSDictionary *)responseObject objectForKey:@"code"] intValue];
            if(code != 100)
            {
                NSString * message = [(NSDictionary *)responseObject objectForKey:@"message"];
                [self.view makeToast:message];
                NSLog(@"%@",message);
                
            }else{
                
//                NSString * token = [(NSDictionary *)responseObject objectForKey:@"token"];
//                NSDictionary *user = [(NSDictionary *)responseObject objectForKey:@"user"];
//                
//                NSDictionary *dict = [DataTool changeType:user];
//                
//                NSString * uid = (NSString *)[dict objectForKey:@"uid"];
//                NSString * username = (NSString *)[dict objectForKey:@"username"];
//                NSString * department = (NSString *)[dict objectForKey:@"department"];
//                NSString * departmentName = (NSString *)[dict objectForKey:@"departmentName"];
//                NSString * img = (NSString *)[dict objectForKey:@"img"];
//                NSString * logo = (NSString *)[dict objectForKey:@"logo"];
//                NSString * name = (NSString *)[dict objectForKey:@"name"];
//                NSString * type = (NSString *)[dict objectForKey:@"type"];
//                //          NSString *type = [[[NSUserDefaults standardUserDefaults] objectForKey:@"type"] stringValue];//取值
//                
//                NSLog(@"%@",type);
//                
//                [userDefaults setObject:token forKey:@"token"];
//                [userDefaults setObject:uid forKey:@"uid"];
//                [userDefaults setObject:username forKey:@"username"];
//                [userDefaults setObject:department forKey:@"department"];
//                [userDefaults setObject:type forKey:@"type"];
//                [userDefaults setObject:img forKey:@"img"];
//                [userDefaults setObject:logo forKey:@"logo"];
//                [userDefaults setObject:name forKey:@"name"];
//                [userDefaults setObject:departmentName forKey:@"departmentName"];
//                
//                [userDefaults setObject:password forKey:@"password"];
//                
//                [userDefaults synchronize];
//                
//                MyTabBarController *myTabBarController = [[MyTabBarController alloc] init];
//                [viewController presentViewController:myTabBarController animated:YES completion:nil];
                
            }
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"%@",error);
            [self.view hideToastActivity];
            [self.view makeToast:@"登录失败"];
        }];

    }
    
}

- (void)handleSwipeFrom:(UISwipeGestureRecognizer*)recognizer {
    // 触发手勢事件后，在这里作些事情
    // 底下是刪除手势的方法
    NSLog(@"handleSwipeFrom");
//    [self.view removeGestureRecognizer:recognizer];
}

- (void)openCalendarView{
    NSLog(@"openCalendarView");
    _calendar.height = 100;
}

- (void)closeCalendarView{
    NSLog(@"closeCalendarView");
    _calendar.height = 200;
}

- (void)clickToNewVisit{
    NSLog(@"clickToNewVisit");
    
    NewVisitViewController *newVisitViewController = [[NewVisitViewController alloc] init];
    [self.navigationController pushViewController:newVisitViewController animated:YES];
    
}

- (void)changeVisit{
    NSLog(@"1111");
}

- (void)addVisit{
    NSLog(@"2222");
}

- (void)clickToselectVisit{
    NSLog(@"11111");
    self.navigationController.navigationBarHidden = YES;
    self.tabBarController.tabBar.hidden = YES;
    AppDelegate * appdelagte = [UIApplication sharedApplication].delegate;
    appdelagte.tabbarControl.bottomView.hidden = YES;

    //背影黑罩
    _backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KSCreenW, KSCreenH)];
    _backView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.6];
    [self.view insertSubview:_backView belowSubview:self.view];
//    [self.view addSubview:_backView];
    
    //    backView.hidden = YES;
    //chuanchuanchuanchaun
    _selectStaffView = [[SelectStaffView alloc]initWithFrame:CGRectMake( 50, 0, KSCreenW-50, KSCreenH)];
    [self.view addSubview:_selectStaffView];
    



}



- (void)closeStaffView{
    
    NSLog(@"88888");
    self.navigationController.navigationBarHidden = NO;
    self.tabBarController.tabBar.hidden = NO;
    AppDelegate * appdelagte = [UIApplication sharedApplication].delegate;
    appdelagte.tabbarControl.bottomView.hidden = NO;
    
    _backView.hidden = YES;
    _selectStaffView.hidden = YES;
    //添加动画，添加到父窗口中，使之从下移动上
//    [UIView animateWithDuration:0.3 animations:^{
//        //父窗口还原
//        CGAffineTransform t = CGAffineTransformIdentity;
//        [self.view setTransform:t];
//        //显示backview,table
//        _backView.alpha = 0;
//        _selectStaffView.alpha = 0;
//        //移动table
//        [_selectStaffView setTransform:CGAffineTransformMakeTranslation(0, _selectStaffView.frame.size.height)];
//    } completion:^(BOOL finished) {
//        [self.view removeFromSuperview];
//    }];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSLog(@".....");
//    self.navigationController.navigationBarHidden = YES;
    [self closeStaffView];
}

#pragma mark --MyClientView delagte

- (void)changeNoticeView:(NSInteger)tag
{
    if (tag == 1111) {//下属拜访
        _isMyVisit = NO;
        _myVisitView.hidden = YES;
        _otherVisitView.hidden = NO;
        
        [_topBtnView.otherClient setTitleColor:darkOrangeColor forState:UIControlStateNormal];
        [_topBtnView.myClient setTitleColor:[UIColor colorWithWhite:0.4 alpha:1] forState:UIControlStateNormal];
        _topBtnView.redLine1.backgroundColor = darkOrangeColor;
        _topBtnView.redLine2.backgroundColor = grayLineColor;
        
        self.navigationItem.leftBarButtonItem  = [ViewTool getBarButtonItemWithTarget:self WithString:@"筛选" WithAction:@selector(clickToselectVisit)];
        
    }else if (tag == 2222){//我的拜访
        _isMyVisit =YES;
        _myVisitView.hidden = NO;
        _otherVisitView.hidden = YES;
        
        [_topBtnView.otherClient setTitleColor:[UIColor colorWithWhite:0.4 alpha:1] forState:UIControlStateNormal];
        [_topBtnView.myClient setTitleColor:darkOrangeColor forState:UIControlStateNormal];
        _topBtnView.redLine1.backgroundColor = grayLineColor;
        _topBtnView.redLine2.backgroundColor = darkOrangeColor;
        
        self.navigationItem.leftBarButtonItem  = nil;
        
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"ExchangeTableViewCell";
    VisitTableViewCell *cell = (VisitTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[VisitTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
//    cell.companyLab.text = _excNameArr[indexPath.row];
//    cell.visitTimeLab.text = _excCodeArr[indexPath.row];
//    cell.addressLab.text = _excValidityArr[indexPath.row];
//    cell.visitStausLab.text = _excIntegralArr[indexPath.row];
    cell.companyLab.text = @"南京盈溪工业自动化有限公司";
    cell.visitTimeLab.text = @"14:30";
    cell.addressLab.text = @"江宁区天元中路126号新城发展中心2栋1512";
    cell.visitStausLab.text = @"待拜访";
    return cell;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

CG_INLINE CGRect
CGRectMake1(CGFloat x,CGFloat y,CGFloat width,CGFloat height)
{
    AppDelegate *app = [UIApplication sharedApplication].delegate;
    return CGRectMake(x * app.autoSizeScaleX, y * app.autoSizeScaleY, width * app.autoSizeScaleX, height * app.autoSizeScaleX);
}

CG_INLINE CGRect
CGRectMake2(CGFloat x,CGFloat y,CGFloat width,CGFloat height)
{
    AppDelegate *app = [UIApplication sharedApplication].delegate;
    return CGRectMake(x, y * app.autoSizeScaleY, width, height * app.autoSizeScaleX);
}

CG_INLINE CGRect
CGRectMake3(CGFloat x,CGFloat y,CGFloat width,CGFloat height)
{
    AppDelegate *app = [UIApplication sharedApplication].delegate;
    return CGRectMake(x, y * app.autoSizeScaleY, width, height);
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
